package com.peng.sell.controller;

import com.lly835.bestpay.model.PayResponse;
import com.peng.sell.dto.OrderDTO;
import com.peng.sell.enums.ResponseCodeEnum;
import com.peng.sell.exception.SellException;
import com.peng.sell.service.OrderService;
import com.peng.sell.service.PayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

@Controller
@RequestMapping("/pay")
@Slf4j
public class PayController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private PayService payService;

    /**
     * 预订单生成
     * @param orderId
     * @param returnUrl
     * @param map
     * @return
     */
    @GetMapping("/create")
    public String create(@RequestParam("orderId") String orderId, @RequestParam("returnUrl") String returnUrl, Map<String,Object> map){
        //查询订单
        OrderDTO orderDTO = orderService.findOne(orderId);
        if(orderDTO==null){
            log.error("订单不存在啊");
            throw new SellException(ResponseCodeEnum.ORDER_NOT_EXIST);
        }
        //发起支付
        PayResponse payResponse = payService.create(orderDTO);
        map.put("payResponse",payResponse);
        map.put("returnUrl",returnUrl);
        return "/pay/create";
    }

    /**
     * 微信支付成功回调
     * @param notifyData
     * @return
     */
    public String notify(@RequestBody String notifyData){
        payService.notify(notifyData);
        return "/pay/success";
    }

}
